home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16237 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.mindspring.com!usenet
  2. From: rudd@mindspring.com (Justin Rudd)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: sprintf() in C++
  5. Date: Wed, 10 Apr 1996 02:08:27 GMT
  6. Organization: MindSpring Enterprises
  7. Message-ID: <4kf5bg$u8a@mule2.mindspring.com>
  8. References: <4kene4$nkb@post.gsfc.nasa.gov>
  9. Reply-To: rudd@mindspring.com
  10. NNTP-Posting-Host: rudd.mindspring.com
  11. X-Newsreader: Forte Free Agent v0.55
  12.  
  13. tycho <vonrosen@nssdca.gsfc.nasa.gov> wrote:
  14.  
  15. >I could use some help with regard to sprintf() in C++.  It seems that 
  16. >cout and cin were invented to avoid printf() and scanf() because the
  17. >latter have variable argument lists and hence can't be checked against
  18. >function prototypes.  But is there any corresponding C++ approach to
  19. >sprintf() and sscanf()?  When I look at various string class functions
  20. >I don't see what to use instead of sprintf() and sscanf().  But when I
  21. >look at my C code, I'm using sprintf() and sscanf() all the time.  It
  22. >seems very clumsy to cast a string object to a character array, use
  23. >sprintf() to write to it and then convert the result back to a string 
  24. >object.  And, of course, using sprintf() means that the compiler can't 
  25. >check against a prototype.  So what am I missing?  I have examined a
  26. >number of standard texts and they don't seem to ever go into this when
  27. >talking about strings.  K&R discuss sprintf() and sscanf() under the
  28. >heading of "In-memory Format Conversion", but these functions do much
  29. >more than that.
  30.  
  31. >As a newcomer to C++ I will appreciate any assistance you can give.
  32.  
  33.  
  34. If you are looking for a C++ way to format a string like sprintf() I
  35. recommend using the strstream class.  It is very simple to use.  
  36.  
  37. //small example
  38.  
  39. char msg[500];
  40.  
  41. ostrstream stream(msg,500);
  42.  
  43. stream << "An Int Value" << 10 << endl;
  44. stream << "A Float Value" << 10.0f << endl;
  45. stream << "Really Simple stuff" << ends << endl;
  46.  
  47. cout << msg;
  48.  
  49.  
  50. Justin Rudd
  51. rudd@mindspring.com
  52. =======================================
  53. It'll work...trust me ;-)
  54. =======================================
  55.  
  56.  
  57.